<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace buwang\service;

use think\facade\Cookie;
use think\facade\Session as SessionAlias;
use app\common\model\User;
use encrypter\Encrypter;
use filter\Inspect;
use app\manage\model\Admin;
use app\manage\model\Member;

class UserService
{
    const session_name = 'current_user';  //当前登录用户的sessionkey
    const key = 'buwangyun#com@buwang';  //加密秘钥

    /**
     * 判断登录密码是否正确
     * @param $username
     * @param $password
     * @return array
     */
    public static function validateLogin($username, $password): array
    {
        return ['rs' => Admin::validateLogin($username, $password), 'error' => Admin::getError()];
    }

    public static function loginAdmin($admin, $trans = false): array
    {
        return ['rs' => Admin::loginAdmin($admin, $trans), 'error' => Admin::getError()];
    }

    public static function validateMember($username, $password): array
    {
        return ['rs' => Member::validateMember($username, $password), 'error' => Member::getError()];
    }

    public static function loginMember($admin, $trans = false): array
    {
        return ['rs' => Member::loginMember($admin, $trans), 'error' => Member::getError()];
    }

    public static function validateUser($username, $password,$member_miniapp_id=null): array
    {
        return ['rs' => User::validateUser($username, $password,$member_miniapp_id), 'error' => User::getError()];
    }

    public static function loginUser($user, $scopes, $trans = false): array
    {
        return ['rs' => User::loginUser($user, $scopes, $trans), 'error' => User::getError()];
    }

    /**
     * 判断是否登录
     * @access public
     * @return boolean
     */
    public static function isLogin(): bool
    {
        if (SessionAlias::has(self::session_name)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取用户详细信息
     * @return array|false|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getUser()
    {
        if (self::isLogin()) {
            $user = User::find(self::getLogin('id'));
            if (empty($user)) return false;
            if ($user['is_lock'] == 0) {
                return $user;
            }
        }
        return false;
    }

    /**
     * 获取登录Session中保存的数据
     * @param string $key (id,username,invite_code)
     * @return false|mixed
     */
    public static function getLogin(string $key)
    {
        if (self::isLogin()) {
            $info = SessionAlias::get(self::session_name);
            $login_info = json_decode(Encrypter::bwDecode($info, self::key), true);
            return empty($key) ? $login_info : $login_info[$key];
        }
        return false;
    }

    /**
     * 设置登录Session
     * @param $param
     * @noinspection PhpVoidFunctionResultUsedInspection
     */
    public static function setLogin($param)
    {
        if (isset($param['id'])) {
            $data = array_merge([
                'id' => $param['id'],
                'login_time' => time(),
            ], $param);
        } else {
            $data = $param;
        }
        $key = Encrypter::bwEncode(json_encode($data), self::key);
        return SessionAlias::set(self::session_name, $key);
    }

    /**
     * 退出Session
     * @access public
     */
    public static function setLogout()
    {
        SessionAlias::delete(self::session_name);
    }


    /**
     * 保存邀请码
     * @return mixed|string
     */
    public static function setInviteCode(): string
    {
        $invite_code = input('invite_code', '', 'htmlspecialchars');
        if (isset($invite_code)) {
            Cookie::set('invite_code', Inspect::filter_escape($invite_code), 3600 * 24);
            return $invite_code;
        }
        return '';
    }

    /**
     * 获取邀请码
     * @return string
     */
    public static function getInviteCode(): string
    {
        if (Cookie::has('invite_code')) {
            return Cookie::get('invite_code');
        }
        return '';
    }

    /**
     * 删除邀请码
     * @noinspection PhpVoidFunctionResultUsedInspection
     */
    public static function delInviteCode()
    {
        return Cookie::delete('invite_code');
    }
}